﻿using DotNet.RateLimiter;
using DotNet.RateLimiter.ActionFilters;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Aliang.WebApiDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    //[RateLimit(PeriodInSec = 20, Limit = 3, Scope = RateLimitScope.Controller)]//控制器上使用
    public class RateLimiterController : ControllerBase
    {
        /// <summary>
        ///  添加RateLimit接口特性
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetNow")]
        [RateLimit(PeriodInSec = 20, Limit = 3)]
        public ActionResult GetNow()
        {
            return Ok(
                new
                {
                    Msg = "当前时间",
                    Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
                }
                );
        }

        /// <summary>
        /// 不添加RateLimit特性接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetYesteyDayNow")]
        public ActionResult GetYesteyDayNow()
        {
            return Ok(
               new
               {
                   Msg = "昨天时间",
                   Value = DateTime.Now.AddDays(-1).ToString("yyyy/MM/dd HH:mm:ss")
        }
               );
        }

        /// <summary>
        /// RateLimit特性结合路由参数接口
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetBeforeTimeByDay/{day}")]
        [RateLimit(PeriodInSec = 20, Limit = 3, RouteParams = "day")]//搭配路由进行使用
        public ActionResult ActionResult(int day)
        {
            return Ok(
             new
             {
                 Msg = $"{day}天前时间",
                 Value = DateTime.Now.AddDays(-day).ToString("yyyy/MM/dd HH:mm:ss")
        }
             );
        }

    }
}
